package com.ppm.server.base.conf;

import com.ppm.common.base.dto.ResultDTO;
import com.ppm.common.base.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @author KwokChiKit
 * @date 2021/4/15 17:38
 * @Description 全局拦截器
 */
@Slf4j
@RestController
@ControllerAdvice
public class GlobalExceptionHandle {

    /**
     * 处理参数异常
     *
     * @param e 异常信息
     * @return 返回内容
     */
    @ExceptionHandler(BaseException.class)
    public ResultDTO handleInvalidArgumentException(BaseException e) {
        e.printStackTrace();
        return new ResultDTO(e.getCode(), e.getMsg(), null);
    }

    /**
     * 处理未知异常
     *
     * @param e 异常信息
     * @return 返回内容
     */
    @ExceptionHandler(Exception.class)
    public ResultDTO handleUnknownException(Exception e) {
        log.error("{}系统抛出异常，异常是：{}，异常信息是：{}", new Date(), e.getClass().getName(), e.getMessage());
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        if (request != null) {
            log.error("请求路径：{}", request.getRequestURL().toString());
        }
        if (response != null) {
            log.error("响应头：{}", response.getHeader("Content-Type"));
        }
        e.printStackTrace();
        BaseException base = new BaseException();
        /**
         * 添加valid校验抛参
         * */
        if (e instanceof BindException){
            BindingResult exceptions  = ((BindException) e).getBindingResult();
            if (exceptions.hasErrors()) {
                List<ObjectError> errors = exceptions.getAllErrors();
                if (!errors.isEmpty()) {
                    // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                    FieldError fieldError = (FieldError) errors.get(0);
                    return ResultDTO.failed(fieldError.getDefaultMessage());
                }
            }
            return  new ResultDTO(400,e.getMessage(),null);
        }
        return new ResultDTO(base.getCode(), base.getMsg(), null);
    }
}
